package com.ychen.springbatch.listener;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * @author chenyuliao
 * @version 1.0
 * @description
 * @date 2020/10/18 21:49
 */
@Configuration
public class ListenerDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job listenerDemoJob() {
        return jobBuilderFactory.get("listenerDemoJob")
                .start(listenerDemoStep1())
                .listener(new MyJobListener())
                .build();
    }

    @Bean
    public Step listenerDemoStep1() {
        return stepBuilderFactory.get("listenerDemoStep1")
                .<String, String>chunk(2)
                .faultTolerant()
                .listener(new MyChunkListener())
                .reader(read())
                .writer(write())
                .build();
    }

    @Bean
    public ItemWriter<String> write() {
        return new ItemWriter<String>() {
            @Override
            public void write(List<? extends String> list) throws Exception {
                for (String item : list) {
                    System.out.println("item: " + item);
                }
            }
        };
    }

    public ItemReader<String> read() {
        return new ListItemReader<>(Arrays.asList("java", "Spring", "mybatis"));
    }

}
